<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-row>
        <el-col>
          <el-button type="primary" @click="addroles">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="roleslist" border style="width: 100%">
        <el-table-column type="expand">
          <!-- 作用域插槽用来创建权限 -->
          <template slot-scope="scope">
            <!-- 利用栅格 -->
            <!-- 遍历一级权限 -->
            <!-- {{ scope.row }} -->
            <el-row
              :class="['border', i1 == 0 ? 'border_first ' : '', 'vcender']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="6">
                <!-- 权限标签 -->
                <el-tag closable @close="closeTag(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="18">
                <!-- 遍历二级权限 -->
                <el-row
                  :class="[
                    'border_first',
                    i2 == 0 ? 'border_top' : '',
                    'vcender'
                  ]"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag type="success" closable>{{
                      item2.authName
                    }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级权限 -->
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                    >
                      {{ item3.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="editroles(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="removeRoles(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-s-tools"
              @click="distibuteRoles(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 这是添加角色消息框 -->
    <el-dialog title="添加角色" :visible.sync="adddialogVisible" width="70%">
      <!-- 内容表单 -->
      <el-form
        ref="formrole"
        :model="formroles"
        :rules="rolesRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formroles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="formroles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="removeAdd">取 消</el-button>
        <el-button type="primary" @click="submitAdd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 这是编辑角色框 -->
    <el-dialog title="修改角色" :visible.sync="editdialogVisible" width="70%">
      <!-- 内容表单 -->
      <el-form
        ref="formedit"
        :model="editrole"
        :rules="rolesRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editrole.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editrole.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="removeAdd">取 消</el-button> -->
        <el-button type="primary" @click="submitedit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配函数对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="DistributedialogVisible"
      width="50%"
      @close="closeID"
    >
      <!-- 树型控件 -->
      <el-tree
        :data="rolestree"
        :props="treeProps"
        show-checkbox
        default-expand-all
        :default-checked-keys="arraydef"
        node-key="id"
        ref="Refroles"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="DistributedialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleslist: [],
      rolestree: [],
      // 权限展开数组的id
      arraydef: [],
      // 用来存储当前点击分配权限的角色id
      nodeID: '',
      // 角色添加
      adddialogVisible: false,
      DistributedialogVisible: false,
      // 添加表单数据对象
      formroles: {
        roleName: '',
        roleDesc: ''
      },
      rolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 编辑表单数据
      editdialogVisible: false,
      editrole: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      // 树型结构的渲染
      treeProps: {
        //  这是树型结构的孩子权限
        children: 'children',
        // 这是树型结构的权限名称
        label: 'authName'
      }
    }
  },
  created() {
    this.getlist()
  },
  methods: {
    async getlist() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色失败')
      }
      //   console.log(res.data)
      this.roleslist = res.data
    },
    // 添加角色
    addroles() {
      this.adddialogVisible = true
    },
    // 添加角色中的取消操作
    removeAdd() {
      // 重置内容
      this.$refs.formrole.resetFields()
      this.adddialogVisible = false
    },
    // 添加角色的确认操作
    async submitAdd() {
      // 提交前先进行预先验证
      this.$refs.formrole.validate(async (valid) => {
        if (!valid) return this.$message.error('请输入正确的信息')
      })
      // 发送请求
      const { data: res } = await this.$http.post('roles', this.formroles)
      //   console.log(res)
      if (res.meta.status !== 201) {
        return this.$message.error('添加角色失败')
      }
      this.$message.success('添加角色成功')
      this.getlist()
      this.adddialogVisible = false
      this.$refs.formrole.resetFields()
    },
    // 编辑权限
    async editroles(roleinfo) {
      const { data: res } = await this.$http.get(`roles/${roleinfo}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('查询角色id失败')
      }
      this.editrole = res.data
      this.editdialogVisible = true
    },
    // 确定编辑
    async submitedit() {
      // 提交前先进行预先验证
      this.$refs.formedit.validate(async (valid) => {
        if (!valid) return this.$message.error('请输入正确的信息')
      })
      // 发起请求
      const { data: res } = await this.$http.post('roles', {
        roleName: this.editrole.roleName,
        roleDesc: this.editrole.roleDesc
      })
      //   console.log(res)
      if (res.meta.status !== 201) {
        return this.$message.error('编辑失败')
      }
      this.$message.success('编辑成功')
      this.getlist()
      this.editdialogVisible = false
    },
    // 监听tag标签的改变
    async closeTag(role, id) {
      const Resules = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // 取消删除
      if (Resules !== 'confirm') {
        this.$message.info('已经取消删除')
      }
      // 确定删除
      //   console.log('确定删除')
      // 确定删除发起axios请求
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${id}`
      )
      console.log(res.data)
      // 在服务端删除成功后，在页面删除，未来防止页面再次刷新导致的关闭,我们利用给作用域插槽赋值的操作进行渲染
      role.children = res.data
    },
    // 删除角色事件
    async removeRoles(rem) {
      // 提醒用户是否要确定删除
      const ResultesRoles = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (ResultesRoles !== 'confirm') {
        this.$message.info('取消了删除')
      }
      this.$message.success('删除成功')
      // 发起删除请求
      this.$http.delete(`roles/${rem}`)
      //   console.log(res)
      this.getlist()
    },
    // 分配函数监听
    async distibuteRoles(info) {
      this.nodeID = info.id
      // 获取数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限失败')
      }
      this.rolestree = res.data
      this.getLeftKeys(info, this.arraydef)
      this.DistributedialogVisible = true
    },
    // 递归回调判断是否是三级权限，同时将该权限的id存储
    getLeftKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getLeftKeys(item, arr)
      })
      //   console.log(arr)
    },
    // 用来清除每次点击分配权限弹框给保存数组的id
    closeID() {
      this.arraydef = []
    },
    // 这个函数是用来点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.Refroles.getCheckedKeys(),
        ...this.$refs.Refroles.getHalfCheckedNodes()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.nodeID}/rights`,
        {
          rids: idStr
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改权限失败')
      }
      this.$message.success('修改权限成功')
      //   console.log(res)
      this.getlist()
      this.DistributedialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
}
.border_first {
  border-top: 1px solid #ccc;
}
.border {
  border-bottom: 1px solid #ccc;
}
.border_top {
  border-top: 0;
}
.vcender {
  display: flex;
  align-items: center;
}
</style>